//
// Created by YE on 2024/2/10.
//
#include "ych_string.h"

void initString(YString *yString) {
    yString->data = (char *) malloc(INITIAL_CAPACITY * sizeof(char));
    if (yString->data == nullptr) {
        exit(EXIT_FAILURE);
    }
    yString->length = 0;
    yString->capacity = INITIAL_CAPACITY;
    yString->data[0] = '\0';
}
void initString(YString *yString, const char * oldStr) {
    yString->length = strlen(oldStr);
    yString->capacity = yString->length+1;
    yString->data = (char *) malloc((yString->capacity) * sizeof(char));
    if (yString->data == NULL) {
        exit(EXIT_FAILURE);
    }
    strcpy(yString->data, oldStr);

}
void appendString(YString *yString, const char *append) {
    size_t appendLen = strlen(append);
    size_t requiredCapacity = yString->length + appendLen + 1;

    if (requiredCapacity > yString->capacity) {
        while (requiredCapacity > yString->capacity)
            yString->capacity *= 2;
        yString->data = (char *) realloc(yString->data, yString->capacity * sizeof(char));
        if (yString->data == nullptr) {
            exit(EXIT_FAILURE);
        }
    }
    strcat(yString->data, append);
    yString->length += appendLen;
}

void copyString(YString *yString, YString *oldStr) {
    yString->data = (char *) malloc(oldStr->capacity * sizeof(char));
    if (yString->data == NULL) {
        exit(EXIT_FAILURE);
    }
    strcpy(yString->data, oldStr->data);
    yString->length = oldStr->length;
    yString->capacity = oldStr->capacity;
}

void destroyString(YString *yString) {
    free(yString->data);
    yString->data = nullptr;
    yString->length = 0;
    yString->capacity = 0;
}